/**
 * Copyright (c) 2023 murenchao
 * taomu is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *       http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package cool.taomu.toolkit.jersey

import com.google.inject.Key
import com.google.inject.TypeLiteral
import com.google.inject.name.Names
import cool.taomu.toolkit.Context
import cool.taomu.toolkit.TaomuGuice
import java.util.ArrayList
import java.util.List
import javax.inject.Inject
import javax.ws.rs.core.Feature
import javax.ws.rs.core.FeatureContext
import org.glassfish.hk2.api.ServiceLocator
import org.glassfish.jersey.server.ResourceConfig
import org.jvnet.hk2.guice.bridge.api.GuiceBridge
import org.jvnet.hk2.guice.bridge.api.GuiceIntoHK2Bridge
import org.slf4j.LoggerFactory

class GuiceResourceConfig extends ResourceConfig {
	val static LOG = LoggerFactory.getLogger(GuiceResourceConfig);

	@Inject
	new(Context jgi) {
		var pks = new ArrayList<String>();
		val injector = jgi.injectorSupplier.get();
		try {
			if (injector.getExistingBinding(Key.get(new TypeLiteral<List<String>>() {
            }, Names.named(TaomuGuice.JESERY_PACKAGES))) !== null) {
				var pk = injector.getInstance(Key.get(new TypeLiteral<List<String>>() {
            }, Names.named(TaomuGuice.JESERY_PACKAGES)));
				pks.addAll(pk);
			}
		} catch (Exception ex) {
			LOG.debug("packages Exception:{}", ex);
		}
		try {
			if (injector.getExistingBinding(Key.get(String, Names.named(TaomuGuice.JESERY_SERVICELOADER_PACKAGES))) !==
				null) {
				var String slpk = injector.getInstance(
					Key.get(String, Names.named(TaomuGuice.JESERY_SERVICELOADER_PACKAGES)));
				pks.add(slpk);
			}
		} catch (Exception ex) {
			LOG.debug("packages Exception:{}", ex);
		}
		var pk = pks.join(",")
		LOG.info("packages:{}", pk);
		packages(pk.split(","));

		register(new Feature() {
			@Inject
			ServiceLocator locator

			override configure(FeatureContext context) {
				if (locator !== null) {
					GuiceBridge.getGuiceBridge().initializeGuiceBridge(locator);
					var GuiceIntoHK2Bridge guiceBridge = locator.getService(GuiceIntoHK2Bridge);
					guiceBridge.bridgeGuiceInjector(injector);
					return true;
				}
				return false
			}
		})
	}

}
